<template>
  <div class="admin-users">
    <div class="page-header">
      <div class="header-left">
        <h1>用户管理</h1>
        <p class="subtitle">管理系统用户和权限</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </div>

    <!-- Search and Filter -->
    <div class="search-section">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名或邮箱..."
          prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
      </div>
      <div class="filter-bar">
        <el-select v-model="roleFilter" placeholder="角色筛选" clearable @change="loadUsers">
          <el-option label="管理员" value="admin" />
          <el-option label="普通用户" value="user" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="loadUsers">
          <el-option label="激活" value="active" />
          <el-option label="禁用" value="disabled" />
        </el-select>
      </div>
    </div>

    <!-- Users Table -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="users"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="username" label="用户名" sortable="custom" min-width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar">
                {{ row.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="email" label="邮箱" min-width="180" />
        
        <el-table-column prop="displayName" label="显示名称" min-width="120">
          <template #default="{ row }">
            {{ row.displayName || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'info'" size="small">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
              {{ row.status === 'active' ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" sortable="custom" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginAt" label="最后登录" width="120">
          <template #default="{ row }">
            {{ row.lastLoginAt ? formatDate(row.lastLoginAt) : '从未登录' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="row.status === 'active' ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
              :disabled="row.role === 'admin' && adminCount <= 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div v-if="total > pageSize" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>

    <!-- Create User Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      title="添加用户"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="createForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="createForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="显示名称">
          <el-input v-model="createForm.displayName" placeholder="请输入显示名称（可选）" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="createForm.password"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-radio-group v-model="createForm.role">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="handleCreate">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- Edit User Dialog -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑用户"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="显示名称">
          <el-input v-model="editForm.displayName" placeholder="请输入显示名称（可选）" />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-radio-group v-model="editForm.role">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="重置密码">
          <el-input
            v-model="editForm.newPassword"
            type="password"
            show-password
            placeholder="留空则不修改密码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleUpdate">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import type { User } from '@/types/auth'

const users = ref<User[]>([])
const loading = ref(false)
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const sortBy = ref('createdAt')
const sortOrder = ref('desc')

const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const createLoading = ref(false)
const editLoading = ref(false)

const createFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

const createForm = reactive({
  username: '',
  email: '',
  displayName: '',
  password: '',
  role: 'user'
})

const editForm = reactive({
  id: '',
  username: '',
  email: '',
  displayName: '',
  role: 'user',
  newPassword: ''
})

const adminCount = computed(() => {
  return users.value.filter(user => user.role === 'admin').length
})

const createRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ]
}

const editRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ]
}

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const loadUsers = async () => {
  loading.value = true
  try {
    // TODO: Implement API call to get users
    // const response = await getUsers({
    //   page: currentPage.value,
    //   size: pageSize.value,
    //   search: searchQuery.value,
    //   role: roleFilter.value,
    //   status: statusFilter.value,
    //   sortBy: sortBy.value,
    //   sortOrder: sortOrder.value
    // })
    // users.value = response.data.items
    // total.value = response.data.total
    
    // Mock data for now
    users.value = [
      {
        id: '1',
        username: 'admin',
        email: 'admin@example.com',
        displayName: '系统管理员',
        role: 'admin',
        status: 'active',
        avatar: '',
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).toISOString(),
        updatedAt: new Date().toISOString(),
        lastLoginAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString()
      },
      {
        id: '2',
        username: 'developer',
        email: 'developer@example.com',
        displayName: '开发者',
        role: 'user',
        status: 'active',
        avatar: '',
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 15).toISOString(),
        updatedAt: new Date().toISOString(),
        lastLoginAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString()
      },
      {
        id: '3',
        username: 'testuser',
        email: 'test@example.com',
        displayName: '',
        role: 'user',
        status: 'disabled',
        avatar: '',
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7).toISOString(),
        updatedAt: new Date().toISOString(),
        lastLoginAt: ''
      }
    ]
    total.value = 3
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  sortBy.value = prop
  sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  loadUsers()
}

const handleCreate = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    createLoading.value = true
    
    // TODO: Implement API call to create user
    // await createUser(createForm)
    
    ElMessage.success('用户创建成功')
    showCreateDialog.value = false
    resetCreateForm()
    loadUsers()
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建用户失败，请重试')
    }
  } finally {
    createLoading.value = false
  }
}

const handleEdit = (user: User) => {
  editForm.id = user.id
  editForm.username = user.username
  editForm.email = user.email
  editForm.displayName = user.displayName || ''
  editForm.role = user.role
  editForm.newPassword = ''
  showEditDialog.value = true
}

const handleUpdate = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // TODO: Implement API call to update user
    // await updateUser(editForm.id, editForm)
    
    ElMessage.success('用户更新成功')
    showEditDialog.value = false
    resetEditForm()
    loadUsers()
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('更新用户失败，请重试')
    }
  } finally {
    editLoading.value = false
  }
}

const handleToggleStatus = async (user: User) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.username}" 吗？`,
      `确认${action}`,
      {
        confirmButtonText: action,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: Implement API call to toggle user status
    // await toggleUserStatus(user.id)
    
    ElMessage.success(`用户${action}成功`)
    loadUsers()
  } catch (error) {
    // User cancelled or error occurred
  }
}

const handleDelete = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: Implement API call to delete user
    // await deleteUser(user.id)
    
    ElMessage.success('用户删除成功')
    loadUsers()
  } catch (error) {
    // User cancelled or error occurred
  }
}

const resetCreateForm = () => {
  createForm.username = ''
  createForm.email = ''
  createForm.displayName = ''
  createForm.password = ''
  createForm.role = 'user'
  createFormRef.value?.resetFields()
}

const resetEditForm = () => {
  editForm.id = ''
  editForm.username = ''
  editForm.email = ''
  editForm.displayName = ''
  editForm.role = 'user'
  editForm.newPassword = ''
  editFormRef.value?.resetFields()
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.admin-users {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-bar {
  flex: 1;
  max-width: 400px;
}

.filter-bar {
  display: flex;
  gap: 12px;
}

.table-card {
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-bar {
    justify-content: stretch;
  }
  
  .filter-bar .el-select {
    flex: 1;
  }
}
</style>